import getUserCard from "../../utils/getUserCard.js";
const utils = require('../../utils/util.js');
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    CurrentPage: 1,
    loadingMoreHidden: 1,
    lists: [],
    IsAgent: 0, //0为分销商，1为代理商
    typeId: 1, //1:我的团队,2:区域资源 区域代理一定是代理商
    AccountBalance: 0,    //账户余额
    curFirstBrokerage: 0, //当前用户等级比例
    searchUid: 0,
    searchName: '',         //搜索人昵称
    btnDialog: { uid: 0, show: false},
  },

  toSign: function (e) {
    let uid = e.currentTarget.dataset.uid;
    this.getJiujiuContract(uid);
  },

  getJiujiuContract: function (uid) {
    wx.request({
      url: app.globalData.host + '/api/Coupon/GetCardApply?uid=' + uid,
      success: function (res) {
        if (res.data.Code == 0) {
          if (res.data.Data) {
            wx.navigateTo({
              url: '/information/uploadDocuments/index?seltoid=' + uid,
            })
          }else{
            var path = encodeURIComponent('jjk-service.html?uid=' + uid +'&storeId=' + app.globalData.storeId + '&rand=' + Math.random());
            wx.navigateTo({
              url: '/pages/h5page/index?url=' + app.globalData.webhost + path,
            })
          }
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      CurrentPage: 1,
      lists: []
    })
    if (options.id) {
      this.setData({
        typeId: options.id
      })
    }
    if (options.id == 1) { //加载我的团队
      wx.setNavigationBarTitle({
        title: '玖玖客户',
      })
    }
    if (options.id == 2) { //加载区域资源
      this.getRegionAgentTeam();
      wx.setNavigationBarTitle({
        title: '区域代理商',
      })
    }
  },

  onShow: function () {
    if (this.data.typeId == 1) {
      this.GetMyTeam();
    }
  },

  //获取我的分销团队
  GetMyTeam: function (nickname = '') {
    var that = this;
    wx.showLoading({title: '加载中',mask: true,})
    wx.request({
      url: app.globalData.host + '/api/Distributor/GetDistributorTeam',
      data: {
        userId: that.data.searchUid > 0 ? that.data.searchUid : app.globalData.userInfo.Uid,
        page: that.data.CurrentPage,
        itemsPerPage: 10,
        nickname: nickname,
        rescure: true
      },
      success: function (res) {
        wx.hideLoading()
        if (res.data.Code == 0) {
          var list = res.data.Data.Items;
          if (!list) {
            return;
          }
          that.initDataList(list);
          that.setData({
            loadingMoreHidden: res.data.Data.TotalPages,
            IsAgent: res.data.Data.Context.IsAgent,
            AccountBalance: res.data.Data.Context.AccountBalance,
            curFirstBrokerage: res.data.Data.Context.DisGrade.FirstBrokerageRise,
          })
          if(that.data.CurrentPage == 1){
            wx.setNavigationBarTitle({
              title: '玖玖客户('+ res.data.Data.TotalItems +')',
            })
          }
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            showCancel: false
          })
        }
      }
    })
  },

  //获取区域运营商下的代理商信息
  getRegionAgentTeam: function (nickname = "") {
    let that = this;
    let uid = that.data.searchUid > 0 ? that.data.searchUid : app.globalData.userInfo.Uid;
    let param = {
      userId: uid,
      storeId: app.globalData.storeId,
      page: that.data.CurrentPage,
      itemsPerPage: 10,
      nickname: nickname
    }
    wx.showLoading({title: '加载中',mask: true})
    wx.request({
      url: app.globalData.host + '/api/Distributor/GetRegionAgentTeam',
      data: param,
      success: function (res) {
        wx.hideLoading();
        if (res.data.Code == 0) {
          var list = res.data.Data.Items;
          if (!list) {
            return;
          }
          that.initDataList(list);
          that.setData({
            loadingMoreHidden: res.data.Data.TotalPages,
            IsAgent: res.data.Data.Context.IsAgent,
          })
          if(that.data.CurrentPage == 1){
            wx.setNavigationBarTitle({
              title: '玖玖客户('+ res.data.Data.TotalItems +')',
            })
          }
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            showCancel: false
          })
        }
      }
    })
  },

  initDataList: function (list) {
    if (this.data.CurrentPage != 1) {
      var preGoods = this.data.lists
      list = preGoods.concat(list);
    }
    var newLists = this.checkUnique(list); //去重
    for (let i = 0; i < newLists.length; i++) {
      newLists[i].ShowLogo = utils.formatAvater(newLists[i].ShowLogo, 'https://static.711688.net.cn/upload/card/source/');
      var FirstBrokerageRise = newLists[i].DisGrade.FirstBrokerageRise;      
      if (parseFloat(FirstBrokerageRise) == 0) {
        newLists[i].DisGrade.FirstBrokerageRiseName = ''
        if(newLists[i].IsAgent == 1){
          newLists[i].DisGrade.FirstBrokerageRiseName = '拓展员'
        }
      }
      if (parseFloat(FirstBrokerageRise) == 40) {
        newLists[i].DisGrade.FirstBrokerageRiseName = '领跑官'
      }
      if (parseFloat(FirstBrokerageRise) == 60) {
        newLists[i].DisGrade.FirstBrokerageRiseName = '经销商'
      }
      if (parseFloat(FirstBrokerageRise) == 80 || 
        parseFloat(FirstBrokerageRise) == 70 || 
        parseFloat(FirstBrokerageRise) == 90 || 
        parseFloat(FirstBrokerageRise) == 96) {
        newLists[i].DisGrade.FirstBrokerageRiseName = '代理商'
      }
      var ExpiredIn = newLists[i].ExpiredIn;
      newLists[i].showDate = ExpiredIn.substr(0, 10);
      newLists[i].version = '';
      if (newLists[i].IndustryCode == 0) {
        newLists[i].version = '个人版';
      }
      if (newLists[i].IndustryCode == 1) {
        newLists[i].version = '共享推广版';
      }
      if (newLists[i].IndustryCode == 2) {
        newLists[i].version = '商家版';
      }
      if (newLists[i].IndustryCode == 3) {
        newLists[i].version = '共享版';
      }
      if (newLists[i].IndustryCode == 4) {
        newLists[i].version = '智慧经营版';
      }
      if (newLists[i].IndustryCode == 5) {
        newLists[i].version = '云点单版';
      } 
      if (newLists[i].IndustryCode == 6) {
        newLists[i].version = '云代货版';
      }      
    }
    this.setData({
      lists: newLists
    })
  },

  // 加载更多
  loadMore: function (e) {
    var that = this;
    if (that.data.loadingMoreHidden > 1 && that.data.CurrentPage < that.data.loadingMoreHidden) {
      var currPage = that.data.CurrentPage;
      that.setData({
        CurrentPage: currPage + 1
      })
      if (that.data.typeId == 1) {
        that.GetMyTeam();
      }
      if (that.data.typeId == 2) {
        that.getRegionAgentTeam();
      }
    } 
  },
  
  onReachBottom: function () {
    this.loadMore();
  },

  //搜索我的团队
  searchByName(e) {
    var value = e.detail.value;
    this.setData({
      CurrentPage: 1,
      lists: [],
      searchUid: 0,
      searchName: ''
    })
    if (this.data.typeId == 1) {
      this.GetMyTeam(value);
    }
    if (this.data.typeId == 2) {
      this.getRegionAgentTeam(value);
    }
  },
  //uid方式搜索的团队
  searchByUid: function(e){
    this.setData({
      CurrentPage: 1,
      lists: [],
      searchUid: e.currentTarget.dataset.uid,
      searchName: e.currentTarget.dataset.name
    })
    if (this.data.typeId == 1) {
      this.GetMyTeam('');
    }
    if (this.data.typeId == 2) {
      this.getRegionAgentTeam('');
    }
  },

  //查看详情
  tapDetails: function (ev) {
    var isShowLevel = 1; //是否显示下级
    var IsAgent = this.data.IsAgent;
    var disLevel = ev.currentTarget.dataset.dislevel;
    if (IsAgent == 0 && disLevel == 2) {
      isShowLevel = 0;
    } else {
      isShowLevel = 1;
    }
    wx.navigateTo({
      url: '/fenxiao/teamDetails/index?userid=' + ev.currentTarget.dataset.userid + "&isShowLevel=" + isShowLevel + '&typeid=' + this.data.typeId,
    })
  },

  //查看名片
  toCardDetails: function (e) {
    var userid = e.currentTarget.dataset.id
    getUserCard(userid, function (cardid) {
      wx.reLaunch({
        url: '/pages/home/index?id=' + cardid,
      })
    })
  },

  //数组去重
  checkUnique: function (array) {
    var temp = [];
    var index = [];
    var l = array.length;
    for (var i = 0; i < l; i++) {
      for (var j = i + 1; j < l; j++) {
        if (array[i].Id === array[j].Id) {
          i++;
          j = i;
        }
      }
      temp.push(array[i]);
      index.push(i);
    }
    return temp;
  },

  //经营报表
  toReport: function(e){
    let uid = e.currentTarget.dataset.uid;
    wx.navigateTo({
      url: '/merchant/merchants/businReports/index?childUid=' + uid + '&parentuid=' + uid + '&isAll=0'
    })
  },
  //微信支付申请
  toWeixinApply: function(e){
    this.toWebPage('pay-wxApply.html?uid=' + e.currentTarget.dataset.uid);
  },
  //支付宝支付申请
  toAlipayApply: function(e){
    this.toWebPage('pay-alipayApply.html?uid=' + e.currentTarget.dataset.uid);
  },
  toWebPage: function(path){
    wx.navigateTo({
      url: '/pages/h5page/index?url=' + encodeURIComponent(app.globalData.webhost + path),
    })
  },

  setDialog: function(e){
    let show = e.currentTarget.dataset.show;
    let uid = e.currentTarget.dataset.uid;
    let btnDialog = this.data.btnDialog;
    btnDialog.show = show == 1;
    btnDialog.uid = uid;
    this.setData({
      btnDialog: btnDialog
    })
  }
})